package com.org.buildcycle2;

import java.io.IOException;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.anddev.andengine.entity.layer.tiled.tmx.util.exception.TMXLoadException;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.PathModifier;
import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.anddev.andengine.entity.modifier.PathModifier.Path;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.entity.text.TickerText;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.HorizontalAlign;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.exception.MultiTouchException;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.SensorManager;
import android.widget.Toast;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;

/**
 * Referenced code by Nicolas Gramlich
 */
public class CharJumpActivity extends BaseGameActivity implements
		IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener {

	private TMXTiledMap mTMXTiledMap;
	protected int mGroundCount;
	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 320;

	public static final int MOVE_RIGHT = 1;
	public static final int MOVE_LEFT = -1;
	public static final int STAND = 0;

	private static final int MaxSpeed_X = 4;
	private static final int jumpSpeed = 6;
	private static final int Gravity = 6;

	public static int currentItem;
	private int tempGravity = Gravity;
	private long previousTime = 0;

	float pValueX;
	private float previousY = 0;
	
	protected Body playerOneBody;
	protected Body playerTwoBody;
	
	protected AnimatedSprite playerOne;
	protected AnimatedSprite playerTwo;
	
	protected static Body doubleJumpItem;
	protected static AnimatedSprite doubleJumpSprite;

	private Camera camera;
	public int doubleJump = 0;
	public int dash = 1;

	boolean player_dead = false;
	boolean invincible_boost = false;

	int timer1 = 0;
	int timer = 0;
	int speed_boost = 1;
	int jump_boost = 0;
	int jump_count = 0;
	int checkpointPlayed = 1;

	private BitmapTextureAtlas speed_item_t;
	private TextureRegion speed_item_tr;
	private Sprite speed_item;
	private BitmapTextureAtlas jump_item_t;
	private TextureRegion jump_item_tr;
	private Sprite jump_item;
	private BitmapTextureAtlas checkpoint_atlas;
	private TextureRegion checkpoint_region;
	private Sprite checkpoint_sprite;
	private BitmapTextureAtlas invincible_item_t;
	private TextureRegion invincible_item_tr;
	private Sprite invincible_item;
	private BitmapTextureAtlas finish_atlas;
	private TextureRegion finish_region;
	private Sprite finish_sprite;
	
	// sheel's variables DONT FUCK WITH MAH SHIT
	private static float mVolume = 1.0f;
	private static Music mMusic;
	private static boolean enableSound;
	private static boolean enableMusic;

	private BitmapTextureAtlas mBitmapTextureAtlas;
	private BitmapTextureAtlas mDoubleJumpTextureAtlas;
	
	private TiledTextureRegion mPlayerOneTextureRegion;
	private TiledTextureRegion mPlayerTwoTextureRegion;
	
	private TiledTextureRegion doubleJumpTextureRegion;

	private BitmapTextureAtlas mOnScreenControlTexture;
	private TextureRegion mOnScreenControlBaseTextureRegion;
	private TextureRegion mOnScreenControlKnobTextureRegion;
	
	private TiledTextureRegion mPlayerTextureRegion;

	private BitmapTextureAtlas mBitmapHud;
	private TiledTextureRegion mHud;

	// Physics implementation setup for gravity of the player
	public PhysicsWorld mPhysicsWorld;

	public float mGravityX;
	public float mGravityY;

	public static Scene mScene;
	protected static boolean isJumping = false;
	protected static boolean inAir = false;
	static boolean upsideDown = false;

	public Shape ground;
	public Shape roof;
	public Shape left;
	public Shape right;

	protected boolean movingRight = false;
	protected boolean movingLeft = false;
	protected boolean alreadyStanding = false;

	protected static int count = 0;
	protected boolean dead = false;
	public Context context;
	private FixtureDef objectFixtureDef;
	private FixtureDef objectFixtureDef1;
	private boolean checkpointActive = false;

	private Sound mPowerUp;
	private Sound mDeath;

	// Font Variables-----------------------
	private BitmapTextureAtlas mFontTexture;
	private Font mFont;
	// -------------------------------------

	// Checkpoint Variables-----------------
	public int checkpointPositionX = 20;
	public int checkpointPositionY = CAMERA_HEIGHT - 50;

	// -------------------------------------

	// Locks the camera and displays a message to user
	@Override
	public Engine onLoadEngine() {

		this.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

		final EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HEIGHT), this.camera)
				.setNeedsSound(true);
		engineOptions.getTouchOptions().setRunOnUpdateThread(true);

		final Engine engine = new Engine(engineOptions);
		context = this;
		try {
			if (MultiTouch.isSupported(this)) {
				engine.setTouchController(new MultiTouchController());

			}
		} catch (final MultiTouchException e) {
			Toast.makeText(this,
					"Sorry your Android Version does NOT support MultiTouch!",
					Toast.LENGTH_LONG).show();
		}

		return engine;
	}

	// Loads the Sprite image and makes a variable for it
	@Override
	public void onLoadResources() {
		SoundFactory.setAssetBasePath("mfx/");
		try {
			this.mPowerUp = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "powerup.ogg");
			this.mDeath = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "death.ogg");
		} catch (final IOException e) {
			Debug.e("Error", e);
		}

		this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mDoubleJumpTextureAtlas = new BitmapTextureAtlas(32, 32,TextureOptions.BILINEAR_PREMULTIPLYALPHA);BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

		this.mPlayerOneTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this,"VirgaChar.png", 0, 0, 4, 8);
		this.mPlayerTwoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this,"VirgaChar.png", 0, 0, 4, 8);
		
		this.doubleJumpTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mDoubleJumpTextureAtlas, this,"speed_item.png", 0, 0, 1, 1);
		this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this,"onscreen_control_base.png", 0, 0);
		this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this,"onscreen_control_knob.png", 128, 0);

		this.speed_item_t = new BitmapTextureAtlas(512, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.speed_item_tr = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.speed_item_t, this, "speed_item.png", 0,0);
		this.mEngine.getTextureManager().loadTexture(this.speed_item_t);

		this.jump_item_t = new BitmapTextureAtlas(512, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.jump_item_tr = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.jump_item_t, this, "jump_item.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.jump_item_t);

		this.invincible_item_t = new BitmapTextureAtlas(512, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.invincible_item_tr = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.invincible_item_t, this,"invincible_item.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.invincible_item_t);

		this.checkpoint_atlas = new BitmapTextureAtlas(512, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.checkpoint_region = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.checkpoint_atlas, this, "box.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.checkpoint_atlas);

		this.finish_atlas = new BitmapTextureAtlas(512, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.finish_region = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.finish_atlas, this, "flag.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.finish_atlas);

		this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas,this.mDoubleJumpTextureAtlas, this.mOnScreenControlTexture);
		this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128,TextureOptions.DEFAULT);
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this,"player.png", 0, 0, 3, 4); // 72x128

		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);

		// ----------------------Text Resources--------------------
		this.mFontTexture = new BitmapTextureAtlas(256, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 24, true, Color.WHITE);

		this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
		this.mEngine.getFontManager().loadFont(this.mFont);
		// --------------------------------------------------------

	}

	// Creates the boundaries, sets the background and creates the sprite on the
	// screen
	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());

		this.mPhysicsWorld = new PhysicsWorld(new Vector2(0,SensorManager.GRAVITY_EARTH), false);

		CharJumpActivity.mScene = new Scene();

		/*
		 * final int centerX = (CAMERA_WIDTH - mBgTexture.getWidth()) / 2; final
		 * int centerY = (CAMERA_HEIGHT - mBgTexture.getHeight()) / 2;
		 * SpriteBackground bg = new SpriteBackground(new Sprite(centerX,
		 * centerY, mBgTexture)); scene.setBackground(bg); //
		 * this.scene.setBackground(new ColorBackground(51, 102, 255));
		 */

		try {
			final TMXLoader tmxLoader = new TMXLoader(this,
					this.mEngine.getTextureManager(),
					TextureOptions.BILINEAR_PREMULTIPLYALPHA,
					new ITMXTilePropertiesListener() {
						@Override
						public void onTMXTileWithPropertiesCreated(
								final TMXTiledMap pTMXTiledMap,
								final TMXLayer pTMXLayer,
								final TMXTile pTMXTile,
								final TMXProperties<TMXTileProperty> pTMXTileProperties) {
							if (pTMXTileProperties.containsTMXProperty(
									"ground", "true")) {
								CharJumpActivity.this.mGroundCount++;
								// This code almost works
								// groundTiles.add(pTMXTile);
							}
						}
					});
			this.mTMXTiledMap = tmxLoader.loadFromAsset(this,
					"tmx/level1virgawider.tmx");

		} catch (final TMXLoadException tmxle) {
			Debug.e(tmxle);
		}
		final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
		mScene.attachChild(tmxLayer);

		CharJumpActivity.mScene.setOnSceneTouchListener(this);

		ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH + 3000, 2);
		roof = new Rectangle(0, 0, CAMERA_WIDTH + 3000, 2);
		left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
		right = new Rectangle(CAMERA_WIDTH + 3000 - 2, 0, 2, CAMERA_HEIGHT);

		final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0,0.5f, 0.5f);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground,BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof,BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, left,BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, right,BodyType.StaticBody, wallFixtureDef);

		CharJumpActivity.mScene.attachChild(ground);
		CharJumpActivity.mScene.attachChild(roof);
		CharJumpActivity.mScene.attachChild(left);
		CharJumpActivity.mScene.attachChild(right);

		CharJumpActivity.mScene.setOnAreaTouchListener(this);

		objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
		objectFixtureDef1 = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
		
		objectFixtureDef.filter.groupIndex = -8;
		objectFixtureDef1.filter.groupIndex = -8;
		
		playerOne = new AnimatedSprite(checkpointPositionX, checkpointPositionY,this.mPlayerOneTextureRegion);
		playerOneBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, playerOne,BodyType.DynamicBody, objectFixtureDef);

		playerTwo = new AnimatedSprite(checkpointPositionX + 5, checkpointPositionY,this.mPlayerTwoTextureRegion);
		playerTwoBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, playerTwo,BodyType.DynamicBody, objectFixtureDef1);
		
		speed_item = new Sprite(650, 290, this.speed_item_tr);
		CharJumpActivity.mScene.attachChild(speed_item);
		invincible_item = new Sprite(400, 290, this.invincible_item_tr);
		CharJumpActivity.mScene.attachChild(invincible_item);
		jump_item = new Sprite(900, 290, this.jump_item_tr);
		CharJumpActivity.mScene.attachChild(jump_item);
		checkpoint_sprite = new Sprite(500, 285, this.checkpoint_region);
		CharJumpActivity.mScene.attachChild(checkpoint_sprite);
		finish_sprite = new Sprite(CAMERA_WIDTH + 920, 285, this.finish_region);

		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(playerOne, playerOneBody, true, true));
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(playerTwo, playerTwoBody, true, true));
		
		animateDude(playerOne, false, STAND);
		animateDude(playerTwo, false, STAND);
		
		final PhysicsHandler physicsHandler = new PhysicsHandler(playerOne);
		final PhysicsHandler physicsHandler1 = new PhysicsHandler(playerTwo);
		
		playerOne.registerUpdateHandler(physicsHandler);
		playerOne.setUserData(playerOneBody);
		CharJumpActivity.mScene.registerTouchArea(playerOne);
		CharJumpActivity.mScene.attachChild(playerOne);
		
		playerTwo.registerUpdateHandler(physicsHandler1);
		playerTwo.setUserData(playerTwoBody);
		CharJumpActivity.mScene.registerTouchArea(playerTwo);
		CharJumpActivity.mScene.attachChild(playerTwo);

		// Player Movement
		final int x1 = 0;
		final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight();
		final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.camera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() {

			@Override
			public void onControlChange(
					final BaseOnScreenControl pBaseOnScreenControl,
					final float pValueX, final float pValueY) {
				if (dead == false) {
					Vector2 velocity = Vector2Pool.obtain(speed_boost
							* 5 * pValueX, getYVelocity(playerOneBody));
					playerOneBody.setLinearVelocity(velocity);
					if (speed_boost * 5 * pValueX > 0
							&& movingRight != true) {
						animateDude(playerOne, upsideDown, MOVE_RIGHT);
						movingLeft = false;
						movingRight = true;
						alreadyStanding = false;
					}
					if (speed_boost * 5 * pValueX < 0
							&& movingLeft != true) {
						animateDude(playerOne, upsideDown, MOVE_LEFT);
						movingRight = false;
						movingLeft = true;
						alreadyStanding = false;
					}
					if (pValueX == 0 && !alreadyStanding) {
						animateDude(playerOne, upsideDown, STAND);
						movingRight = false;
						movingLeft = false;
						alreadyStanding = true;
					}
				}
			}
	
			@Override
			public void onControlClick(
					final AnalogOnScreenControl pAnalogOnScreenControl) {
				/* Nothing. */
			}
		});

		// Used for the display to focus on the character as he moves.
		velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		velocityOnScreenControl.getControlBase().setAlpha(0.5f);
		velocityOnScreenControl.getControlBase().setScaleCenter(0, 128);
		velocityOnScreenControl.getControlBase().setScale(1.25f);
		velocityOnScreenControl.getControlKnob().setScale(1.25f);
		velocityOnScreenControl.refreshControlKnobPosition();

		CharJumpActivity.mScene.setChildScene(velocityOnScreenControl);
		CharJumpActivity.mScene.registerUpdateHandler(this.mPhysicsWorld);
		MyContactListener groundTouchListener = new MyContactListener(playerOne, playerOneBody);
		this.mPhysicsWorld.setContactListener(groundTouchListener);
		/* Create the sprite and add it to the scene. */
		final AnimatedSprite player = new AnimatedSprite(350, CAMERA_HEIGHT - 50, this.mPlayerTextureRegion);
		this.camera.setChaseEntity(playerOne);
		mScene.attachChild(player);

		final Path path = new Path(5).to(300, CAMERA_HEIGHT - 35).to(420, CAMERA_HEIGHT - 35).to(300, CAMERA_HEIGHT - 35).to(420, CAMERA_HEIGHT - 35).to(300, CAMERA_HEIGHT - 35);

		player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() {
				@Override
				public void onPathStarted(final PathModifier pPathModifier,
						final IEntity pEntity) {

				}

				@Override
				public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
						switch (pWaypointIndex) {
						case 0:
							player.animate(new long[] { 150, 150, 150 }, 4, 6,
									true);
							break;
						case 1:
							player.animate(new long[] { 150, 150, 150 }, 9, 11,
									true);
							break;
						case 2:
							player.animate(new long[] { 150, 150, 150 }, 4, 6,
									true);
							break;
						case 3:
							player.animate(new long[] { 150, 150, 150 }, 9, 11,
									true);
							break;
						}
					}

					@Override
					public void onPathWaypointFinished(
							final PathModifier pPathModifier,
							final IEntity pEntity, final int pWaypointIndex) {

					}

					@Override
					public void onPathFinished(
							final PathModifier pPathModifier,
							final IEntity pEntity) {

					}
				})));

		mScene.registerUpdateHandler(new IUpdateHandler() {
			@Override
			public void onUpdate(float pSecondsElapsed) {
				if (playerOne.collidesWith(speed_item)) {
					if (dead == false) {
						CharJumpActivity.this.mPowerUp.play();
						speed_boost = 2;
						mScene.detachChild(speed_item);
						speed_item = null;
						timer = 0;
					}
				}

				if (speed_boost == 2) {
					timer += 1;
					if (timer >= 275)
						speed_boost = 1;
				}

				if (playerOne.collidesWith(jump_item)) {
					if (dead == false) {
						CharJumpActivity.this.mPowerUp.play();
						jump_boost = 3;
						mScene.detachChild(jump_item);
						jump_item = null;
					}
				}

				if (jump_count == 3)
					jump_boost = 0;

				if (playerOne.collidesWith(invincible_item)) {
					if (dead == false) {
						CharJumpActivity.this.mPowerUp.play();
						invincible_boost = true;
						mScene.detachChild(invincible_item);
						invincible_item = null;
						timer1 = 0;
					}
				}

				if (playerOne.collidesWith(checkpoint_sprite)) {
					checkpointPlayed++;
					checkpointActive = true;
					mScene.detachChild(checkpoint_sprite);
					checkpoint_sprite.setPosition(10000, 10000);
					final Text CHECKPOINT = new TickerText(getXposition(),
							getYposition(), mFont, "Checkpoint Activated!",
							HorizontalAlign.CENTER, 10);
					CHECKPOINT
							.registerEntityModifier(new SequenceEntityModifier(
									new ParallelEntityModifier(
											new AlphaModifier(3, 0.0f, 1.0f),
											new ScaleModifier(5, 0.5f, 1.0f)),
									new RotationModifier(0, 0, 360)));
					mScene.attachChild(CHECKPOINT);

				}

				/*
				if (dude.collidesWith(finish_sprite)) {
					checkpointActive = true;
					mScene.detachChild(finish_sprite);
					mScene.detachChild(dude);
					camera.setChaseEntity(null);
					body.setTransform(12, 9.4f, 0);
					dead = true;
					final Text WIN = new TickerText(
							getXposition(),
							getYposition(),
							mFont,
							"Congratulations!\nSomehow you have managed to\ncomplete this near impossible game.",
							HorizontalAlign.CENTER, 10);
					WIN.registerEntityModifier(new SequenceEntityModifier(
							new ParallelEntityModifier(new AlphaModifier(3,
									0.0f, 1.0f), new ScaleModifier(10, 0.5f,
									1.0f)), new RotationModifier(5, 5, 360)));
					mScene.attachChild(WIN);

				}
				*/
				if (invincible_boost == true) {
					timer1 += 1;
					if (timer1 >= 275)
						invincible_boost = false;
				}

				if (playerOne.collidesWith(player)) {
					if (invincible_boost == false) {
						if (dead == false) {
							if (player_dead == false) {
								CharJumpActivity.this.mDeath.play();
								mScene.detachChild(playerOne);
								camera.setChaseEntity(null);
								dead = true;
								respawn();
								final Text text = new TickerText(
										getXposition(),
										getYposition(),
										mFont,
										"You died and have been respawned.\n Be more careful!",
										HorizontalAlign.CENTER, 10);
								text.registerEntityModifier(new SequenceEntityModifier(
										new ParallelEntityModifier(
												new AlphaModifier(3, 0.0f, 1.0f),
												new ScaleModifier(8, 0.5f, 1.0f)),
										new RotationModifier(0, 0, 360)));
								text.setBlendFunction(GL10.GL_SRC_ALPHA,
										GL10.GL_ONE_MINUS_SRC_ALPHA);
								mScene.attachChild(text);

							}
						}
					}

					else {
						player_dead = true;
						mScene.detachChild(player);
					}

				}

			}

			@Override
			public void reset() {
				// TODO Auto-generated method stub

			}

		});

		return CharJumpActivity.mScene;
	}

	@Override
	public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
			final ITouchArea pTouchArea, final float pTouchAreaLocalX,
			final float pTouchAreaLocalY) {
		return true;
	}

	@Override
	public void onLoadComplete() {

	}

	// When the screen is touched it calls the jump routine to make the sprite
	// jump
	@Override
	public boolean onSceneTouchEvent(final Scene pScene,
			final TouchEvent pSceneTouchEvent) {
		if (pSceneTouchEvent.isActionDown()) {
			// final AnimatedSprite face = (AnimatedSprite) pTouchArea ;
			if (isJumping == false)
				if (jump_boost == 3)
					jump_count += 1;
			this.jumpDude(playerOne);
		}

		return true;
	}

	// Creates gravity in the y axis according to screen position
	@Override
	public void onAccelerometerChanged(
			final AccelerometerData pAccelerometerData) {
		this.mGravityX = pAccelerometerData.getX();
		this.mGravityY = pAccelerometerData.getY();

		long currentTime = System.currentTimeMillis();

		/*
		 * float xSpeed = this.mGravityX; if(xSpeed <=1 && xSpeed >-1) xSpeed =
		 * 0; else if(xSpeed > .5) { animateDude(dude,upsideDown,MOVE_RIGHT);
		 * if(xSpeed > MaxSpeed_X) xSpeed = MaxSpeed_X; } else if(xSpeed < -.5)
		 * { animateDude(dude,upsideDown,MOVE_LEFT); if(xSpeed < -MaxSpeed_X)
		 * xSpeed = -MaxSpeed_X;
		 * 
		 * }
		 */

		if (currentTime - previousTime > 200) {
			previousTime = currentTime;

			if (mGravityY - previousY > 1) {
				tempGravity = Gravity;
				upsideDown = false;
				inAir = true;
				animateDude(playerOne, upsideDown, STAND);
			} else if (mGravityY - previousY < -1) {
				tempGravity = -Gravity;
				inAir = true;
				upsideDown = true;
				animateDude(playerOne, upsideDown, STAND);
			}

		}
		previousY = mGravityY;

		final Vector2 gravity = Vector2Pool.obtain(0, tempGravity);
		this.mPhysicsWorld.setGravity(gravity);

		Vector2Pool.recycle(gravity);

	}

	@Override
	public void onResumeGame() {
		super.onResumeGame();

		this.enableAccelerometerSensor(this);
	}

	@Override
	public void onPauseGame() {
		super.onPauseGame();

		this.disableAccelerometerSensor();
	}

	// applies a velocity vector to the sprite and makes it jump
	private void jumpDude(final AnimatedSprite face) {
		if (isJumping == false) {
			if (getCurrentItem() == 0) {

				Body faceBody = (Body) face.getUserData();
				Vector2 velocity = Vector2Pool.obtain(0, jump_boost + 2
						* jumpSpeed);
				animateDude(playerOne, upsideDown, STAND);
				faceBody.setLinearVelocity(velocity);
				Vector2Pool.recycle(velocity);
				setIsJumping(true);
			} else {
				Body faceBody = (Body) face.getUserData();
				Vector2 velocity = Vector2Pool.obtain(0, jumpSpeed);
				animateDude(playerOne, upsideDown, STAND);
				faceBody.setLinearVelocity(velocity);
				Vector2Pool.recycle(velocity);
				setIsJumping(true);
			}
		}
	}

	// This function acts as if it implements the actual animation of the
	// sprite.
	public static void animateDude(AnimatedSprite dude, boolean UpsideDown,
			int direction) {
		if (direction == STAND) {
			if (UpsideDown == true) {
				dude.animate(new long[] { 100, 100 }, 28, 29, true);
			} else {
				dude.animate(new long[] { 100, 100 }, 0, 1, true);
			}
		} else if (direction == MOVE_RIGHT) {
			if (UpsideDown == true) {
				dude.animate(new long[] { 200, 200, 200 }, 24, 26, true);
			} else {
				dude.animate(new long[] { 200, 200, 200 }, 4, 6, true);
			}
		} else if (direction == MOVE_LEFT) {
			if (UpsideDown == true) {
				dude.animate(new long[] { 200, 200, 200 }, 20, 22, true);
			} else {
				dude.animate(new long[] { 200, 200, 200 }, 8, 10, true);
			}
		}
	}

	public static void setIsJumping(boolean temp) {
		isJumping = temp;
	}

	public static boolean getUpsideDown() {
		return upsideDown;
	}

	public float getYVelocity(Body body) {
		Vector2 velocity = body.getLinearVelocity();
		return velocity.y;
	}

	public static void setCurrentItem(int item) {
		currentItem = item;
	}

	public int getCurrentItem() {
		return currentItem;
	}

	public float getXposition() {
		return camera.getCenterX() - 175;
	}

	public float getYposition() {
		return camera.getCenterY();
	}

	public void respawn() {
		// dude.setPosition(checkpointPositionX, checkpointPositionY);
		camera.setCenter(mScene.getX() + CAMERA_WIDTH / 2, mScene.getY()
				+ CAMERA_HEIGHT / 2);
		if (checkpointActive) {
			playerOneBody.setTransform(16, 9.4f, 0);
		} else {
			playerOneBody.setTransform(1, 9.4f, 0);
		}
		mScene.attachChild(playerOne);
		camera.setChaseEntity(playerOne);
		dead = false;
	}
	
	
	
	// setting the settings
	private static void setSettings(){
		if(enableMusic == true){
			if(!mMusic.isPlaying()){
				mMusic.setVolume(mVolume);
				mMusic.play();
			}
		}else{
			mMusic.pause();
		}
		if(enableSound == true){
			// play sounds
		}else{
			// don't play sounds
		}
	}
	
	// setting game volume
	public static void setMusicVolume(float vol){
		mVolume = vol;
	}
	
	// toggling ingame sound
	public static void toggleSounds(boolean isSound){
		enableSound = isSound;
	}
	
	// toggling ingame music
	public static void toggleMusic(boolean isMusic){
		enableMusic = isMusic;
	}
	
	
}
